package com.sense.kukoo.biz_media.vm

import android.util.Log
import androidx.lifecycle.MutableLiveData
import com.sense.kukoo.common.event.SubscriptionChangedEvent
import com.sense.kukoo.common.mvvm.model.BaseMvvmModel
import com.sense.kukoo.common.mvvm.vm.BaseViewModel
import com.sense.kukoo.common.repo.Repo
import com.sense.kukoo.common.repo.bean.*
import org.greenrobot.eventbus.EventBus

class MediaDetailViewModel:BaseViewModel() {

    private val TAG: String = javaClass.simpleName

    private var bookId :String? = null

    private var mIndex = 3
    private val mPageSize = 20

    var mData: BookDetailsBean? = null

    val action_back:MutableLiveData<Boolean> = MutableLiveData()
    val action_download:MutableLiveData<Boolean> = MutableLiveData()
    val action_share:MutableLiveData<Boolean> = MutableLiveData()
    val action_more:MutableLiveData<Boolean> = MutableLiveData()
    val action_reportSuccess:MutableLiveData<Boolean> = MutableLiveData()
    val enableLoadMore:MutableLiveData<Boolean> = MutableLiveData(true)
    val mMediaListData:MutableLiveData<ArrayList<MediaListDetailItemBean>> = MutableLiveData()

    override fun createModel(): BaseMvvmModel? = null

    override fun initData() {}

    fun setFromData(id :String){
        bookId = id
    }

    fun onBack(){
        action_back.postValue(true)
    }

    fun onDownload(){
        action_download.postValue(true)
    }

    fun onShare(){
        action_share.postValue(true)
    }

    fun onMore(){
        action_more.postValue(true)
    }

    fun refreshData(){
        toView(ACTION_SHOW_DIALOG)
        request {
            //
            val result = Repo.http.bookDetails(bookId!!)
            if (result.success){
                val bean: BookDetailsBean = result.data!!
                mData = bean
                //
                val asc = Repo.bookSequence.get(bean.idOfBook())
                if(asc == 1){
                    //正序，默认
                    mData!!.localAsc = 1 //序列化有问题，重新赋值
                    mIndex = 3 //复位
                    formateAndShowData()
                }else{
                    val ascResult = Repo.http.bookQueryPage(mData!!.idOfBook(), 1, mPageSize, asc)
                    if (ascResult.success){
                        mIndex = 2
                        val data: QueryPageBean<BookItemBean> = ascResult.data!!
                        val records :ArrayList<BookItemBean> = data.records
                        //
                        mData!!.localAsc = asc
                        mData!!.bookItems!!.clear()
                        mData!!.bookItems!!.addAll(records)
                        formateAndShowData()
                    } else {
                        Log.e(TAG, "result=" + ascResult.msg)
                        ascResult.msg.let { sendHintMessage(it) }
                    }
                }
            } else {
                Log.e(TAG, "result=" + result.msg)
                result.msg.let { sendHintMessage(it) }
            }
            toView(ACTION_HIDE_DIALOG)
        }
    }

    fun loadMore(){
        request {
            val result = Repo.http.bookQueryPage(mData!!.idOfBook(), mIndex, mPageSize, (mData!!.localAsc ?: 1))
            if (result.success){
                mIndex++
                val data: QueryPageBean<BookItemBean> = result.data!!
                val records :ArrayList<BookItemBean> = data.records
                //
                mData!!.bookItems!!.addAll(records)
                formateAndShowData()
            } else {
                Log.e(TAG, "result=" + result.msg)
                result.msg.let { sendHintMessage(it) }
            }
        }
    }

    fun reverseSort(){
        toView(ACTION_SHOW_DIALOG)
        var asc = mData!!.localAsc
        asc = if (asc==0) 1 else 0
        request {
            val result = Repo.http.bookQueryPage(mData!!.idOfBook(), 1, mPageSize, asc)
            if (result.success){
                mIndex = 2
                val data: QueryPageBean<BookItemBean> = result.data!!
                val records :ArrayList<BookItemBean> = data.records
                //
                Repo.bookSequence.set(mData!!.idOfBook(), asc)
                mData!!.localAsc = asc
                mData!!.bookItems!!.clear()
                mData!!.bookItems!!.addAll(records)
                formateAndShowData()
            } else {
                Log.e(TAG, "result=" + result.msg)
                result.msg.let { sendHintMessage(it) }
            }
            toView(ACTION_HIDE_DIALOG)
        }
    }

    private fun checkCanLoadMore(){
        //加载更多
        if(mData!!.bookItems!!.size >= mData!!.numberOfChapter()){
            enableLoadMore.postValue(false)
        }else{
            enableLoadMore.postValue(true)
        }
    }

    fun formateAndShowData(){
        mData?.let { bookDetailsBean ->
            val list = arrayListOf<MediaListDetailItemBean>()

            list.add(MediaListDetailItemBean(MediaListDetailItemBean.TYPE_MEDIA_TITLE, bookDetailsBean, null))
            //
            val itemType:Int
            when (bookDetailsBean.type) {
                BookBean.TYPE_PODCAST -> {
                    itemType = MediaListDetailItemBean.TYPE_PODCAST_LIST_ITEM
                }
                BookBean.TYPE_SHORT_AUDIO -> {
                    itemType = MediaListDetailItemBean.TYPE_SHORTAUDIO_LIST_ITEM
                }
                else -> {
                    itemType = MediaListDetailItemBean.TYPE_AUDIOBOOK_LIST_ITEM
                }
            }
            bookDetailsBean.bookItems!!.forEach {
                list.add(MediaListDetailItemBean(itemType, bookDetailsBean, it))
            }
            //
            mMediaListData.postValue(list)
            checkCanLoadMore()
        }
    }

    fun subscription(){
        toView(ACTION_SHOW_DIALOG)
        request {
            //
            val result = Repo.http.subscription("" + mData!!.id)
            if (result.success){
                val isSubscription:Boolean = !(1 == mData!!.isSubscription)
                mData!!.isSubscription = if(isSubscription) 1 else 0
                formateAndShowData()
                EventBus.getDefault().post(SubscriptionChangedEvent(mData!!.idOfBook(),
                                                                    isSubscription,
                                                                    SubscriptionChangedEvent.FROM_DETAIL))
            } else {
                Log.e(TAG, "result=" + result.msg)
                result.msg.let { sendHintMessage(it) }
            }
            toView(ACTION_HIDE_DIALOG)
        }
    }

    fun setSubscription(event: SubscriptionChangedEvent){
        if(event.from != SubscriptionChangedEvent.FROM_DETAIL && event.bookId == mData!!.idOfBook()){
            mData!!.isSubscription = if(event.isSubscribe) 1 else 0
            formateAndShowData()
        }
    }

    fun report(type:Int){
        toView(ACTION_SHOW_DIALOG)
        request {
            //
            val id = mData!!.idOfBook().toString()
            val result = Repo.http.report(id, type)
            if (result.success){
                action_reportSuccess.postValue(true)
            } else {
                Log.e(TAG, "result=" + result.msg)
                result.msg.let { sendHintMessage(it) }
            }
            toView(ACTION_HIDE_DIALOG)
        }
    }

    /*fun listen(
        bookId: Long,
        bookItemId: Long,
        total: Long,
    ){
        request {
            val result = mModel.listen(bookId, bookItemId, total)
            if (result.success){
                LoggerManager.d(TAG, "listen-save")
            } else {
                LoggerManager.e(TAG, "listen-save-error " + result.msg)
            }
        }
    }*/
}